package com.sptpc.myalarm;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.TimePicker;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements TimePicker.OnTimeChangedListener {
    public static final String ACTION_ALARM ="com.book.action.set_alarm";
    private AlarmManager am = null;
    private TimePicker timePicker;
    private int myhourOfDay = 0;
    private int myminute = 0;
    String text;
    private Calendar calendar = Calendar.getInstance();
    PendingIntent sender;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timePicker = super.findViewById(R.id.tp_time);
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(this);
        Intent i = new Intent();
        i.setAction(ACTION_ALARM);
        sender = PendingIntent.getBroadcast(MainActivity.this,0,i,PendingIntent.FLAG_CANCEL_CURRENT);
        myhourOfDay = timePicker.getCurrentHour();
        myminute = timePicker.getCurrentMinute();
        registerBroadCastReceiver();
    }
    public void clickSet(View v)
    {
        am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),sender);
        Log.d("JInxz", "clickSet: " + calendar.getTime());
    }

    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
        calendar.set(Calendar.MINUTE,minute);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        myhourOfDay = hourOfDay;
        myminute = minute;
        Log.d("JINxz", "onTimeChanged: "+ myminute +"  " + myhourOfDay );
    }

    private void registerBroadCastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_ALARM);
        AlarmReceiver AlarmReceiver = new AlarmReceiver();
        registerReceiver(AlarmReceiver,filter);
        //注册
    }
}
